<template>
  <a-modal
      :visible="visible"
      title="佣金规则"
      :width="'600px'"
      :is="true"
      @ok="handleOk"
      @cancel="onClose"
  >
    <div
        style="max-height: 600px; overflow: auto; padding-right: 4px"
    >
      <a-alert type="warning">
        <template #description>
          <p>
            1、无升档只能有一档，无法新增，而按照合同数还是合同金额，都可以创建最多10档。
          </p>
          <p>
            2、档位下限是达到这个档位的目标值，必须为大于0的整数，最低档从0开始无需更改，允许
            中途添加删除档位 ，但至少保留一个。
          </p>
          <p>
            3、奖励如果是固定就是达到哪个档位，直接奖励固定金额，要求是正整数，不得低于上一档。
            提成比例，可以是从0-90，最多支持2位小数，不得低于上一档。
          </p>
          <p>
            4、结算是按照自然月整体结算，核算值在哪个区间，则享受对应档位的提成比例，基础提成
            不累计计算，只算达标档。
          </p>
        </template>
      </a-alert>

      <a-form ref="ruleRef" class="mt-10" layout="vertical" :model="ruleParam">
        <a-form-item
            label="佣金规则"
            name="name"
            :rules="[{ required: true, message: '请输入佣金规则名称' }]"
        >
          <a-input
              placeHolder="输入佣金规则"
              v-model:value="ruleParam.name"
          ></a-input
          >
        </a-form-item>
      </a-form>

      <div class="mt-10">
        <span class="mr-5">升档方式</span>
        <a-radio-group
            v-model:value="ruleParam.compute_type"
            :options="upshiftMode"
            @change="upshiftChange"
        />
      </div>
      <div class="mt-10">
        <span class="mr-5">提成方式</span>
        <a-radio-group
            v-model:value="ruleParam.divide_type"
            :options="commissionMode"
        />
      </div>
      <div class="mt-10">
        <span style="font-weight: 600">招商专员提成</span>
      </div>
      <a-table
          class="mt-10"
          :columns="columns"
          :dataSource="ruleParam.divide_config"
          :pagination="false"
      >
        <template #bodyCell="{ column, record, index }">
          <template v-if="column.key == 'name'">
            <a-input
                placeHolder="输入名称"
                v-model:value="record.title"
            ></a-input>
          </template>
          <template v-if="column.key == 'down'">
            <a-input-number
                placeHolder="输入下限"
                min="0"
                :disabled="index == 0 || record.compute_type == 1"
                v-model:value="record.threshold"
            ></a-input-number>
          </template>
          <template v-if="column.key == 'ratio'">
            <a-input-number
                placeHolder="输入比例"
                :min="
                index == 0 ? 0 : ruleParam.divide_config[index - 1].divide_num
              "
                :max="ruleParam.divide_type==3?'':90"
                :precision="2"
                v-model:value="record.divide_num"
            >
              <template #addonAfter>{{ unit }}</template>
            </a-input-number>
          </template>
          <template v-if="column.key == 'action'">
            <a-button
                type="link"
                @click="addDivideConfig"
                v-if="ruleParam.compute_type != 1"
            >新增档位
            </a-button
            >
            <a-button
                type="link"
                @click="delDivideConfig(index)"
                danger
                v-if="index != 0"
            >删除
            </a-button
            >
          </template>
        </template>
      </a-table>

      <div class="mt-10">
        <span style="font-weight: 600">开启招商管理提成</span>
        <a-switch
            style="margin: 0 5px"
            :checked="ruleParam.is_manage == 1"
            @change="ruleParam.is_manage = ruleParam.is_manage == 0 ? 1 : 0"
            checked-children="开"
            un-checked-children="关"
        />
        <span style="font-size: 12px"
        >开启后，匹配了这个模板的招商团队经理，可额外获得整组业绩提成</span
        >
      </div>
      <a-table
          class="mt-10"
          border
          :columns="columns"
          :dataSource="ruleParam.manage_config"
          :pagination="false"
      >
        <template #bodyCell="{ column, record, index }">
          <template v-if="column.key == 'name'">
            <a-input
                placeHolder="输入名称"
                v-model:value="record.title"
            ></a-input>
          </template>
          <template v-if="column.key == 'down'">
            <a-input-number
                placeHolder="输入下限"
                min="0"
                :disabled="index == 0 || record.compute_type == 1"
                v-model:value="record.threshold"
            ></a-input-number>
          </template>
          <template v-if="column.key == 'ratio'">
            <a-input-number
                placeHolder="输入比例"
                :min="
                index == 0 ? 0 : ruleParam.manage_config[index - 1].divide_num
              "
                :max="ruleParam.divide_type==3?'':90"
                :precision="2"
                v-model:value="record.divide_num"
            >
              <template #addonAfter>{{ unit }}</template>
            </a-input-number>
          </template>
          <template v-if="column.key == 'action'">
            <a-button
                type="link"
                @click="addManageConfig"
                v-if="ruleParam.compute_type != 1"
            >新增档位
            </a-button
            >
            <a-button
                type="link"
                @click="delManageConfig(index)"
                danger
                v-if="index != 0"
            >删除
            </a-button
            >
          </template>
        </template>
      </a-table>
      <div class="mt-10">
        <span style="font-weight: 600">开启渠道提成</span>
        <a-switch
            style="margin: 0 5px"
            :checked="ruleParam.is_channel == 1"
            @change="ruleParam.is_channel = ruleParam.is_channel == 0 ? 1 : 0"
            checked-children="开"
            un-checked-children="关"
        />
        <span style="font-size: 12px">
          开启后，匹配了这个模板的渠道人员，可额外获得绩提成。</span
        >
      </div>

      <a-table
          class="mt-10"
          border
          :columns="columns"
          :pagination="false"
          :dataSource="ruleParam.channel_config"
      >
        <template #bodyCell="{ column, record, index }">
          <template v-if="column.key == 'name'">
            <a-input
                placeHolder="输入名称"
                v-model:value="record.title"
            ></a-input>
          </template>
          <template v-if="column.key == 'down'">
            <a-input-number
                placeHolder="输入下限"
                min="0"
                :disabled="index == 0 || record.compute_type == 1"
                v-model:value="record.threshold"
            ></a-input-number>
          </template>
          <template v-if="column.key == 'ratio'">
            <a-input-number
                placeHolder="输入比例"
                :min="
                index == 0 ? 0 : ruleParam.channel_config[index - 1].divide_num
              "
                :max="ruleParam.divide_type==3?'':90"
                :precision="2"
                v-model:value="record.divide_num"
            >
              <template #addonAfter>{{ unit }}</template>
            </a-input-number>
          </template>
          <template v-if="column.key == 'action'">
            <a-button
                type="link"
                @click="addChannelConfig"
                v-if="ruleParam.compute_type != 1"
            >新增档位
            </a-button
            >
            <a-button
                type="link"
                @click="delChannelConfig(index)"
                danger
                v-if="index != 0"
            >删除
            </a-button
            >
          </template>
        </template>
      </a-table>
    </div>
  </a-modal>
</template>

<script>
import {reactive, toRefs, ref, watch, computed} from "vue";
import request from "../../../../common/utils/request";
import {message} from "ant-design-vue";

export default {
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    editId: {
      type: Number,
      default: 0,
    },
  },

  setup(props, context) {
    // 规则提交参数
    const ruleParam = reactive({
      name: "",
      compute_type: 1, //升档方式;1=无升档2=合同数量3=合同金额
      divide_type: 1, //提成方式;1=固定比例2=阶梯比例3=阶梯固定金额
      divide_config: [
        {title: "", threshold: 0, divide_num: 10, divide_unit: "%"},
      ],
      is_manage: 1,
      manage_config: [
        {title: "", threshold: 0, divide_num: 10, divide_unit: "%"},
      ],
      is_channel: 1,
      channel_config: [
        {title: "", threshold: 0, divide_num: 10, divide_unit: "%"},
      ],
    });

    const unit = computed(() => {
      return ruleParam.divide_type == 3 ? "元" : "%";
    });

    const addDivideConfig = () => {
      if (ruleParam.divide_config.length < 10) {
        ruleParam.divide_config.push({
          title: "",
          threshold: 0,
          divide_num: 10,
          divide_unit: "%",
        });
      } else {
        message.error("最多只可添加10条规则！");
      }
    };

    const delDivideConfig = (index) => {
      ruleParam.divide_config.splice(index, 1);
    };

    // 管理规则等
    const addManageConfig = () => {
      if (ruleParam.manage_config.length < 10) {
        ruleParam.manage_config.push({
          title: "",
          threshold: 0,
          divide_num: 10,
          divide_unit: "%",
        });
      } else {
        message.error("最多只可添加10条规则！");
      }
    };

    const delManageConfig = (index) => {
      ruleParam.manage_config.splice(index, 1);
    };

    // 渠道规则
    const addChannelConfig = () => {
      if (ruleParam.channel_config.length < 10) {
        ruleParam.channel_config.push({
          title: "",
          threshold: 0,
          divide_num: 10,
          divide_unit: "%",
        });
      } else {
        message.error("最多只可添加10条规则！");
      }
    };
    const delChannelConfig = (index) => {
      ruleParam.channel_config.splice(index, 1);
    };

    const columns = [
      {
        title: "档位名称",
        key: "name",
      },
      {
        title: "档位下限",
        key: "down",
      },
      {
        title: "提成比例",
        key: "ratio",
      },
      {
        title: "操作",
        key: "action",
        width: 120,
      },
    ];

    const upshiftMode = [
      {
        label: "无升档",
        value: 1,
      },
      {
        label: "合同数量",
        value: 2,
      },
      {
        label: "合同金额",
        value: 3,
      },
    ];
    const commissionMode = ref([
      {
        label: "固定比例",
        value: 1,
      },
    ]);

    const upshiftChange = (val) => {
      console.log(val);
      if (val.target.value == 1) {
        commissionMode.value = [
          {
            label: "固定比例",
            value: 1,
          },
        ];
        ruleParam.divide_type = 1;

        if (props.editId == 0) {
          // 编辑的时候，从其他的切回来，改成默认的
          ruleParam.divide_config =
              ruleParam.divide_config.length > 1
                  ? [ruleParam.divide_config[ruleParam.divide_config.length - 1]]
                  : [{title: "", threshold: 0, divide_num: 10, divide_unit: "%"}];
          ruleParam.is_manage = 1;
          ruleParam.manage_config =
              ruleParam.manage_config.length > 1
                  ? [ruleParam.manage_config[ruleParam.manage_config.length - 1]]
                  : [{title: "", threshold: 0, divide_num: 10, divide_unit: "%"}];
          ruleParam.is_channel = 1;
          ruleParam.channel_config =
              ruleParam.channel_config.length > 1
                  ? [ruleParam.channel_config[ruleParam.channel_config.length - 1]]
                  : [{title: "", threshold: 0, divide_num: 10, divide_unit: "%"}];
        }
      } else {
        ruleParam.divide_type = 2;
        commissionMode.value = [
          {
            label: "阶梯比例",
            value: 2,
          },
          {
            label: "阶梯固定金额",
            value: 3,
          },
        ];
      }
    };

    const ruleRef = ref();

    // 操作
    const onClose = () => {
      context.emit("close");
    };
    const handleOk = () => {
      ruleRef.value.validateFields().then(() => {
        if (props.editId) {
          //编辑
          const param = {
            ...ruleParam,
            id: props.editId,
          };
          console.log(param);
          request
              .put("/org", "/business/customer/commissionChange", param)
              .then((res) => {
                console.log(res);
                message.success("修改成功");
                context.emit("save");
              });
        } else {
          //新增
          request
              .post("/org", "/business/customer/commissionAdd", ruleParam)
              .then((res) => {
                console.log(res);
                message.success("添加成功");
                context.emit("save");
              });
        }
      });
    };

    const getRuleDetail = () => {
      request
          .get("/org", "/business/customer/commissionDetail", {
            id: props.editId,
          })
          .then((res) => {
            console.log(res.data);
            const ruleData = res.data;
            ruleParam.name = ruleData.name;
            ruleParam.compute_type = ruleData.compute_type;
            ruleParam.divide_type = ruleData.divide_type;
            ruleParam.divide_config = ruleData.divide_config;
            ruleParam.is_manage = ruleData.is_manage;
            ruleParam.manage_config = ruleData.manage_config;
            ruleParam.is_channel = ruleData.is_channel;
            ruleParam.channel_config = ruleData.channel_config;
            commissionMode.value =
                ruleParam.compute_type == 1
                    ? [
                      {
                        label: "固定比例",
                        value: 1,
                      },
                    ]
                    : [
                      {
                        label: "阶梯比例",
                        value: 2,
                      },
                      {
                        label: "阶梯固定金额",
                        value: 3,
                      },
                    ];
          });
    };

    const reset = () => {
      ruleParam.name = "";
      ruleParam.compute_type = 1;
      ruleParam.divide_type = 1; //提成方式;1=固定比例2=阶梯比例3=阶梯固定金额
      ruleParam.divide_config = [
        {title: "", threshold: 0, divide_num: 10, divide_unit: "%"},
      ];
      ruleParam.is_manage = 1;
      ruleParam.manage_config = [
        {title: "", threshold: 0, divide_num: 10, divide_unit: "%"},
      ];
      ruleParam.is_channel = 1;
      ruleParam.channel_config = [
        {title: "", threshold: 0, divide_num: 10, divide_unit: "%"},
      ];
    };

    watch(
        () => props.visible,
        (val) => {
          if (val == true) {
            console.log(props.editId);
            if (props.editId != 0) {
              getRuleDetail();
            } else {
              reset();
            }
          }
        },
        {
          immediate: true,
        }
    );

    return {
      upshiftMode,
      upshiftChange,
      commissionMode,
      columns,
      onClose,
      handleOk,
      ruleParam,
      addDivideConfig,
      delDivideConfig,
      addManageConfig,
      delManageConfig,
      addChannelConfig,
      delChannelConfig,
      ruleRef,
      unit,
    };
  },
};
</script>

<style lang="less" scoped>
:deep(.ant-alert-description) {
  font-size: 12px;

  p {
    margin-bottom: 6px;
  }
}

:deep(.ant-alert-with-description.ant-alert-no-icon) {
  padding: 6px 10px;
}
</style>
